package com.zhdl.modules.demo.hardware_connect;

import cn.hutool.core.util.HexUtil;
import com.project.common.thread.ThreadScheduledPool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class ConnectManager implements ReceiverMessageInterface{
    @Resource
    ThreadPoolTaskScheduler threadPoolTaskScheduler;
    private LinkDeviceProvider linkDeviceProvider;

    public void setLinkDeviceProvider(LinkDeviceProvider linkDeviceProvider) {
        this.linkDeviceProvider = linkDeviceProvider;
        threadPoolTaskScheduler.scheduleWithFixedDelay(() -> {
            for (LinkDevice linkDevice : linkDeviceProvider.getDeviceList()) {
                linkDevice.checkOnline();
            }
        },1000);
    }

    @Override
    public void receiverMsg(String port, byte[] data) {
        log.info(port+": "+ HexUtil.encodeHexStr(data));
        if (linkDeviceProvider!=null){
            for (LinkDevice linkDevice : linkDeviceProvider.getDeviceList()) {
                if (linkDevice.getPort().equals(port)) {
                    linkDevice.setLastMsg(HexUtil.encodeHexStr(data));
                    linkDevice.setLastMsgTime(System.currentTimeMillis());
                }
            }
        }
    }
    public List<LinkDevice> getCurrentLink(){
        if (linkDeviceProvider == null){
            return new ArrayList<>();
        }else{
            return linkDeviceProvider.getDeviceList();
        }
    }

}
